﻿using AutoTask.DAL;
using AutoTask.Model;
using RpcCacheClient.Interface;
using RpcHelper;

namespace AutoTask.Collect.Collect
{
    internal class TaskItemCollect : ITaskItemCollect
    {
        private static readonly DelayDataSave<SyncItemResult> _SyncStatus = new DelayDataSave<SyncItemResult>(_Save, 2, 10);
        private IAutoTaskItemDAL _BasicDAL;
        private ICacheController _Cache;
        public TaskItemCollect(IAutoTaskItemDAL dal,
            ICacheController cache)
        {
            _Cache = cache;
            _BasicDAL = dal;
        }
        private static void _Save(ref SyncItemResult[] datas)
        {
            RpcClient.RpcClient.Unity.Resolve<IAutoTaskItemDAL>().SyncState(datas);
        }

        public AutoTaskItem[] Gets(Guid taskId, int verNum)
        {
            string key = string.Join("_", "TaskItem", taskId.ToString("N"), verNum);
            if (this._Cache.TryGet(key, out AutoTaskItem[] items))
            {
                return items;
            }
            items = this._BasicDAL.Gets(taskId);
            this._Cache.Set(key, items, new TimeSpan(1, 0, 0, 0));
            return items;
        }


        public void ExecComplate(SyncItemResult result)
        {
            _SyncStatus.AddData(result);
        }
    }
}
